/**
 * @description 视图组件-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const fs = require('fs')
const ox = require('@daelui/oxjs')
const Service = require('./service.js')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 同步环境
  */
  syncEnvir (action) {
    // 解析数据
    return this.solveAction(action).then(async action => {
      let params = action.params || {}
      // 查询路径数据
      let pathList = []
      try {
        // 查询所有的分组数据
        let res = await this.$router.getControllInstance({path: '/tigerlair/dictionary'}).queryAll({}, {
          action: {},
          query: {},
          params: {
            cat: 'register-path',
            status: '1'
          }
        })
        let list = res.data
        list = Array.isArray(list) ? list : []
        pathList = list
      } catch (e) {
        pathList = []
      }
      // 查询适配器数据
      let repList = []
      try {
        // 查询所有的分组数据
        let res = await this.$router.getControllInstance({path: '/tigerlair/dictionary'}).queryAll({}, {
          action: {},
          query: {},
          params: {
            cat: 'register-rep',
            status: '1'
          }
        })
        let list = res.data
        list = Array.isArray(list) ? list : []
        repList = list
      } catch (e) {
        repList = []
      }
      // 查询所有的发布数据
      let list = await this.$router.getControllInstance({path: '/tigerlair/comprelease'}).queryAll({}, {
        action: {},
        params: {
          status: '1'
        },
        excute: {
          operators: [
            {field: 'status', operator: 'EQUAL'}
          ],
          sort: [
            {field: 'createTime', by: 'desc'},
            {field: 'order', by: 'desc'}
          ]
        }
      })
      list = list.data
      list = Array.isArray(list) ? list : []
      let vmap = {}
      list = list.filter(item => {
        let key = item.name + ':' + item.version
        if (vmap[key]) {
          return false
        }
        vmap[key] = 1
        return true
      })
      list = list.map(item => {
        let node = {
          name: item.name,
          version: item.version,
          path: item.path,
          type: item.type,
          text: item.text,
          cat: item.cat,
          main: item.main,
          property: item.property,
          icon: item.icon
        }
        if (item.mainCompile) {
          node.mainCompile = item.mainCompile
        } else {
          node.mainCode = item.mainCode
        }
        if (item.propertyCompile) {
          node.propertyCompile = item.propertyCompile
        } else {
          node.propertyCode = item.propertyCode
        }
        // 依赖
        let deps = []
        if (item.deps) {
          try {
            deps = JSON.parse(item.deps)
            deps = Array.isArray(deps) ? deps : []
            deps = deps.filter(item => {
              return !!item.path && String(item.status) !== '0'
            })
            deps = deps.map(item => {
              return item.path
            })
          } catch (e) {}
        }
        if (deps && deps.length) {
          node.deps = deps
        }
        // 根路径
        let rootUrls = []
        if (item.rootUrls) {
          try {
            rootUrls = JSON.parse(item.rootUrls)
            rootUrls = Array.isArray(rootUrls) ? rootUrls : []
            rootUrls = rootUrls.filter(item => {
              // 路径列表匹配
              let node = pathList.find(node => node.id === item.pathId && String(node.status) === '1')
              if (node && node.value && /\w/.test(node.value) && !item.url) {
                item.url = node.value
              }
              return !!item.url && String(item.status) !== '0'
            })
            rootUrls = rootUrls.map(item => {
              return item.url
            })
          } catch (e) {}
        }
        if (rootUrls && rootUrls.length) {
          node.rootUrls = rootUrls
        }
        // 适配器
        let reps = []
        if (item.reps) {
          try {
            reps = JSON.parse(item.reps)
            reps = Array.isArray(reps) ? reps : []
            reps = reps.filter(item => {
              return !!item.repId && String(item.status) !== '0'
            })
          } catch (e) {}
        }
        if (reps && reps.length) {
          reps = reps.flatMap(item => {
            let node = repList.find(node => node.id === item.repId && String(node.status) === '1')
            if (node && node.value) {
              try {
                let list = JSON.parse(node.value)
                list = Array.isArray(list) ? list : []
                list = list.filter(item => {
                  return !!item.tes && !!item.mat
                })
                return list
              } catch (e) {}
            }
            return []
          })
          reps = reps.filter(node => node.tes && node.mat)
          reps.forEach(item => {
            delete item.id
          })
          node.reps = reps
        }
        return node
      })
      // 组件注册表文件
      let constant = this.route.scope.CONFIG.constant
      let path = constant.poolPath + '/prod'
      if (!fs.existsSync(path)) {
        filer.buildPath(path)
      }
      path += '/' + (constant.componentRegistryFile || 'components.json')
      let success = 0
      // 文件写入
      try {
        let content = JSON.stringify(list, null, ' ')
        fs.writeFileSync(
          path, content
        )
        success = 1
      } catch (e) {
        success = 0
      }
      return {data: list, success: success}
    })
  }
}

module.exports = Controller